<script setup lang="ts">
import { Delete, Download, Refresh, RefreshRight } from "@element-plus/icons-vue"
import { ComponentPublicInstance, computed, onMounted, reactive, ref, watch } from "vue"
import {
  IAuditRequestData,
  IGetApplyListFileResponseData,
  IGetApplyListRequestData,
  IGetApplyListResponseData,
  IGetMultiConditionQueryResponseData
} from "@/api/files/types/files"
import { usePagination } from "@/hooks/usePagination"
import { auditFileApi, deleteFilesApi, fileDownloadApi, getFileApplyListApi } from "@/api/files"
import { IGetDepartmentData } from "@/api/department/types/department"
import { getDepartmentIdAndNameList } from "@/api/department"
import { GetProjectIdAndNameList } from "@/api/project"
import { IGetProjectIdAndNameResponseData } from "@/api/project/types/project"
import { useUserStore } from "@/store/modules/user"
import { openDownload, hasAnthority, previewOnNewTab, showPromptMessage } from "@/utils"
import { ElMessageBox, TableInstance } from "element-plus"
import { IUserInfoData } from "@/api/login/types/login"
import { IGetAdminByNameData } from "@/api/admin/types/admin"
import { getAdminByNameDataApi } from "@/api/admin"

onMounted(async () => {
  await getProjectDataList()
  getFilesDataList()
})

const loading = ref(false)
const userStore = useUserStore()
const userInfo = userStore.userInfo as IUserInfoData
const searchData = reactive<IGetApplyListRequestData>({
  theYear: "",
  projectId: undefined,
  isPass: undefined,
  isNecessary: undefined,
  uploaderId: undefined,
  departmentId: undefined
})
// 查询
const necessaryOptions = [
  {
    label: "补充资料",
    value: 0
  },
  {
    label: "必要资料",
    value: 1
  }
]

const auditStatusObj = {
  0: "未审核",
  1: "驳回",
  2: "通过"
}
const passOptions = [
  {
    label: "驳回",
    value: 0
  },
  {
    label: "通过",
    value: 1
  }
]
const activeNames = ref<number>()
const FilesData = ref<IGetApplyListResponseData[]>([])
const DepartmentData = ref<IGetDepartmentData[]>([])
const ProjectData = ref<IGetProjectIdAndNameResponseData[]>([])
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const refreshing = ref(false)
const getFilesDataList = () => {
  if (refreshing.value) return
  refreshing.value = true
  loading.value = true
  getFileApplyListApi(
    { page: paginationData.currentPage, size: paginationData.pageSize, departmentId: userInfo.departmentId },
    searchData
  )
    .then((res) => {
      res.data.list.map((el) => {
        el.files.map((file, index) => {
          const current = file
          const next = el.files[index + 1]
          if (index < el.files.length - 1) {
            if (next.version > current.version) {
              current.versionType = "old"
            } else {
              current.versionType = "new"
            }
          } else {
            current.versionType = "new"
          }
        })
      })
      FilesData.value = res.data.list
      paginationData.total = res.data.total
    })
    .catch(() => {
      FilesData.value = []
    })
    .finally(() => {
      refreshing.value = false
      loading.value = false
    })
}
defineExpose({ getFilesDataList })

const getDepartmentDataList = () => {
  getDepartmentIdAndNameList({ name: "", departmentId: userInfo.departmentId })
    .then((res) => {
      DepartmentData.value = res.data.list
    })
    .catch(() => {
      DepartmentData.value = []
    })
}
getDepartmentDataList()

const getProjectDataList = async () => {
  const result = await GetProjectIdAndNameList({ name: "", departmentId: searchData.departmentId })
  ProjectData.value = result.data.list
}
const AdminData = ref<IGetAdminByNameData[]>([])

const getAdminData = () => {
  getAdminByNameDataApi({ name: "", departmentId: searchData.departmentId }).then((res) => {
    AdminData.value = res.data.users
  })
}
getAdminData()
const resetSearch = () => {
  searchData.projectId = undefined
  searchData.departmentId = undefined
  searchData.isNecessary = undefined
  searchData.theYear = ""
  searchData.isPass = undefined
  if (paginationData.currentPage === 1) {
    getFilesDataList()
  }
  paginationData.currentPage = 1
}

const handleRefresh = () => {
  getFilesDataList()
}

// 下载
const downloadItems = ref<IGetMultiConditionQueryResponseData[]>([])
const downloadIds = computed(() => {
  return downloadItems.value.map((item) => item.id)
})

type types = Element | ComponentPublicInstance | null
const tableRefs = ref<{ [key: number]: types }>({})
watch(activeNames, (newV, oldV) => {
  if (oldV) {
    const tableRef = tableRefs.value[oldV] as TableInstance
    tableRef && tableRef.clearSelection()
  }
})
const handleSelectionChange = (val: IGetMultiConditionQueryResponseData[]) => {
  downloadItems.value = val
}

const handleDownload = (data: IGetApplyListFileResponseData) => {
  fileDownloadApi(userStore.userInfo!.id, [data.id]).then((res) => {
    openDownload(res.blob, res.fileName)
  })
}
const handleBatchDownload = () => {
  loading.value = true
  fileDownloadApi(userStore.userInfo!.id, downloadIds.value).then((res) => {
    openDownload(res.blob, res.fileName)
    loading.value = false
  })
}
const handleBatchDelete = (row: IGetApplyListResponseData) => {
  if (activeNames.value) {
    ElMessageBox.confirm(
      `正在删除${row.departmentName}的${row.isNecessary ? "必要文件" : "补充文件"}，确认删除？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(() => {
      activeNames.value &&
        deleteFilesApi({ ids: downloadIds.value, applyId: activeNames.value }).then(() => {
          showPromptMessage("success", "删除成功")
          getFilesDataList()
        })
    })
  }
}
// 审核
const auditData = reactive<IAuditRequestData>({
  fileId: undefined,
  isPass: undefined,
  applyId: undefined,
  cause: ""
})
const auditFile = ref<IGetApplyListFileResponseData>()
const auditDialogVisible = ref(false)
const handleAudit = (row: IGetApplyListFileResponseData, applyId: number) => {
  auditFile.value = row
  auditData.applyId = applyId
  auditDialogVisible.value = true
  auditData.fileId = row.id
}
const handleConfirmAudit = () => {
  auditFileApi(auditData).then(() => {
    showPromptMessage("success", "审核成功")
    getFilesDataList()
    auditDialogVisible.value = false
  })
}
const handlePreview = (row: IGetApplyListFileResponseData) => {
  previewOnNewTab(row.url)
}
watch([() => paginationData], getFilesDataList, { deep: true })

watch(
  [() => searchData.theYear, () => searchData.isNecessary, () => searchData.isPass, () => searchData.projectId],
  getFilesDataList,
  {
    deep: true
  }
)

watch(
  [() => searchData.departmentId],
  () => {
    searchData.uploaderId = undefined
    getProjectDataList()
    getAdminData()
    getFilesDataList()
  },
  {
    deep: true
  }
)
</script>

<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中">
    <el-card shadow="never" class="my-5">
      <el-form inline ref="inlineFormRef" :model="searchData">
        <el-form-item v-if="userInfo.authority === '2'" prop="departmentId" label="办学单位">
          <el-select filterable v-model="searchData.departmentId" placeholder="选择办学单位">
            <el-option v-for="item in DepartmentData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="projectId" label="培训项目">
          <el-select filterable v-model="searchData.projectId" placeholder="选择培训项目">
            <el-option v-for="item in ProjectData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="uploaderId" label="上传者">
          <el-select filterable v-model="searchData.uploaderId" placeholder="选择上传者">
            <el-option v-for="item in AdminData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="year" label="立项年度">
          <el-date-picker v-model="searchData.theYear" type="year" value-format="YYYY" placeholder="选择立项年度" />
        </el-form-item>
        <el-form-item prop="year" label="是否通过">
          <el-select filterable v-model="searchData.isPass" placeholder="选择审核状态">
            <el-option v-for="item in passOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="year" label="资料类型">
          <el-select filterable v-model="searchData.isNecessary" placeholder="选择资料类型">
            <el-option v-for="item in necessaryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div class="flex justify-end">
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="mt-5">
        <el-collapse v-if="FilesData.length > 0" accordion v-model="activeNames">
          <el-collapse-item :name="item.id" v-for="item in FilesData" :key="item.id">
            <template #title>
              <div class="flex items-center">
                <span>{{ item.departmentName }}</span>
                <div class="text-blue-400 text-sm ml-5 font-semibold">{{ item.theYear }}</div>
                <!-- 悬浮气泡显示完整项目名 -->
                <div :title="item.projectName" class="text-gray-500 text-xs ml-5 text-center w-80">
                  <!-- <el-tooltip v-if="item.projectName" placement="top" effect="dark" :offset="5" :show-arrow="false">
                    <template #content>
                      <span>{{ item.projectName }}</span>
                    </template>

                  </el-tooltip> -->
                  <div class="w-full one" v-if="item.projectName">
                    {{ item.projectName }}
                  </div>
                  <span v-else>未知项目</span>
                </div>

                <!-- 备份 -->
                <!-- <div class="text-gray-500 text-xs ml-5 text-center w-20 one">
                  {{ item.projectName ?? "未知项目" }}
                </div> -->
                <div class="w-20 flex justify-center">
                  <el-tag class="ml-5" :type="item.isNecessary ? 'danger' : 'info'">{{
                    item.isNecessary ? "必要资料" : "补充资料"
                  }}</el-tag>
                </div>
                <span class="text-gray-300 text-xs ml-5" v-if="item.note">备注信息:{{ item.note }}</span>
              </div>
            </template>
            <el-descriptions>
              <el-descriptions-item>
                <div class="flex">
                  <el-button
                    type="primary"
                    :disabled="downloadIds.length === 0"
                    :icon="Download"
                    @click="handleBatchDownload"
                  >
                    批量下载
                  </el-button>
                  <el-button
                    v-if="hasAnthority('file.delete')"
                    type="danger"
                    :disabled="downloadIds.length === 0"
                    :icon="Delete"
                    @click="handleBatchDelete(item)"
                  >
                    批量删除
                  </el-button>
                </div>

                <el-table
                  class="mt-2"
                  :ref="
                    (el) => {
                      tableRefs[item.id] = el
                    }
                  "
                  @selection-change="handleSelectionChange"
                  border
                  :data="item.files"
                  style="width: 100%"
                >
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="name" label="文件名称" show-overflow-tooltip />
                  <el-table-column prop="version" label="版本号" />
                  <el-table-column prop="versionType" label="版本比较">
                    <template #default="scope">
                      <el-tag type="success" v-if="scope.row.versionType === 'new'"> 新版本 </el-tag>
                      <el-tag type="info" v-if="scope.row.versionType === 'old'"> 旧版本 </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="cause" label="驳回原因" />
                  <!-- Flag1 -->
                  <el-table-column prop="auditStatus" label="审核状态">
                    <template #default="scope">
                      <el-tag
                        :type="scope.row.auditStatus === 0 ? '' : scope.row.auditStatus === 1 ? 'danger' : 'success'"
                      >
                        {{ auditStatusObj[(scope.row as IGetApplyListFileResponseData).auditStatus] }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="note" label="备注信息" />
                  <el-table-column fixed="right" label="操作" width="220" align="center">
                    <template #default="scope">
                      <el-button type="primary" text bg size="small" @click="handlePreview(scope.row)">预览</el-button>
                      <el-button type="primary" text bg size="small" @click="handleAudit(scope.row, item.id)"
                        >审核</el-button
                      >
                      <el-button type="primary" text bg size="small" @click="handleDownload(scope.row)">下载</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </el-collapse>
        <div v-else>
          <el-empty />
        </div>
      </div>
      <div class="mt-5">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!--    审核弹窗-->
    <el-dialog v-model="auditDialogVisible" align-center title="审核文件" width="50%">
      <div>
        <el-form label-width="100" ref="auditFormRef" :model="auditData">
          <el-form-item prop="isPass" label="是否通过" :rules="{ required: true }">
            <el-select v-model="auditData.isPass" placeholder="选择">
              <el-option v-for="item in passOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="cause" label="驳回原因">
            <el-input type="textarea" v-model="auditData.cause" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmAudit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-table__row.green) {
  background-color: #f0f9eb;
}

:deep(.el-table__row.gray) {
  background-color: #ebeef5;
}
</style>
